<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="./main.js"></script>
  </head>
  <body>
    <input type="file" accept="image/*" multiple />
    <button>上传图片</button>
    <img src="" alt="" />

    <button>下载文件</button>
    <button>下载pdf文件</button>

    <script>
      const btn = document.querySelectorAll("button");
      const ipt = document.querySelector("input");
      const img = document.querySelector("img");
      btn[0].addEventListener("click", async function (e) {
        const data = new FormData();
        data.append("file", ipt.files[0]);
        //多图上传
        // const newAarr = [...ipt.files];
        // newAarr.forEach((ele) => {
        //   console.log(ele[0], ele);
        //   data.append("file", ele);
        // });
        try {
          const res = await axios({
            method: "post",
            url: "http://localhost:3000/upload",
            data,
            headers: {
              "Content-Type": "multipart/form-data",
            },
          });
          console.log(res);
          img.src = res.data.data.path;
          // img.src = res.data.data[0].path; //多图上传
        } catch (error) {
          console.log(error);
        }
      });

      btn[1].addEventListener("click", async function (e) {
        const res = await axios.get("http://localhost:3000/download", {
          responseType: "blob",
        });
        console.log(res);
        const url = window.URL.createObjectURL(res.data);

        const a = document.createElement("a");
        a.href = url;
        a.download = "example.txt.gz"; // 下载的文件名
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      });
      btn[2].addEventListener("click", async function (e) {
        const res = await axios.get("http://localhost:3000/downloadPdf", {
          responseType: "blob",
        });
        const url = window.URL.createObjectURL(res.data);
        window.open(url);
      });
    </script>
  </body>
</html>
